using UnityEngine;
using System.Collections;

public class OldManManager : MonoBehaviour {

	public static OldManManager Instance;
	
	Transform thisTransform;
//	Transform enemyTransform;
//	Transform playerTransform;

	public enum CHARACTER
	{
		PLAYER,
		ENEMY,
		DEFAULT
	};
	
	public CHARACTER characterType 			= CHARACTER.DEFAULT;

	public GameObject startPosition;
	public GameObject endPosition;
	
	public Material[] animationMaterial;
	
	private Vector3 newPosition 			= default(Vector3);
	
	private float xPosition					= default(float);	
	
	private float endTime 					= 0.0F;
	private float defaultTime 				= 0.0F;
	private float multiplier				= 0.0F;
	
	void Awake () 
	{
		Instance = this;
		thisTransform = transform;
		
//		if ( characterType == CHARACTER.ENEMY )
//			enemyTransform = transform;
//		else
//			playerTransform = transform;
		
	}
	
	void Start ()
	{
		endTime = LevelManager.Instance.endTime;
		defaultTime = LevelManager.Instance.defaultTime;
		multiplier = LevelManager.Instance.MULTIPLIER;
		
		if ( characterType == CHARACTER.ENEMY )
		{
			StartCoroutine( "MoveOldManAI" );
		}	
		
//		Debug.Log(thisTransform.name);
	}
	
	public void StartMoving ()
	{
		if ( characterType == CHARACTER.PLAYER )
		{
//			Debug.Log(this.name);
			StartCoroutine( "MoveOldMan" );
		}
	}
	
	IEnumerator MoveOldMan ()
	{
		xPosition = ( endPosition.transform.position.x - startPosition.transform.position.x ) * multiplier;
		newPosition = new Vector3( thisTransform.position.x + xPosition, thisTransform.position.y, thisTransform.position.z );
		
		//change to walk position
		this.gameObject.renderer.material = animationMaterial[1];
		
		//start walking
		while( Vector3.Distance(thisTransform.position, newPosition) > 1.0 ) //thisTransform.position != newPosition )
		{		
			thisTransform.position = Vector3.MoveTowards(thisTransform.position, newPosition, 5.0f * Time.deltaTime);
			yield return 0;
		}
		//change to idle position
		this.gameObject.renderer.material = animationMaterial[0];
	}
	
	IEnumerator MoveOldManAI ()
	{
		float distance = endPosition.transform.position.x - startPosition.transform.position.x;
		
		//randomize time for each enemyAI
		float time = Random.Range( defaultTime + 5.0f, endTime ); 	
		//compute speed depending on time and distance
		float speed = distance / time;				
		
		Vector3 newPosition = new Vector3( endPosition.transform.position.x, thisTransform.position.y, thisTransform.position.z );
		
		while( Vector3.Distance(thisTransform.position, newPosition) > 1.0  )
		{
			thisTransform.position = Vector3.MoveTowards(thisTransform.position, newPosition, speed * Time.deltaTime);
			yield return 0;
		}
	}
	
	void OnTriggerEnter ( Collider thisObject )
	{
		if ( characterType != CHARACTER.ENEMY )
		{
			if ( thisObject.tag == "Finish" )
			{
				StopCoroutine( "MoveOldManAI" );
				StopCoroutine( "MoveOldMan" );
	           	LevelManager.Instance.FinishRace ();
			}
		}
	}
}
